﻿using Core.Ndatax.Domain;
using Core.Ndatax.Domain.Dto;
using Core.Ndatax.Infrastructure.Common;
using Core.Ndatax.Infrastructure.Entitys;
using Core.Ndatax.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Linq;
using Xman.Extensions.Core;

namespace Core.Ndatax.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class NdataxController : ControllerBase
    {
        private readonly ILogger<NdataxController> _logger;
        private readonly ResServer _httpClientServer;
        private readonly IBllRequest _bllRequest;
        private readonly RisServer _risServer;
        private readonly RisOptions _options;

        public NdataxController(ILogger<NdataxController> logger, RisServer risServer, IBllRequest bllRequest, ResServer httpClientServer, IOptions<RisOptions> options)
        {
            _logger = logger;
            _bllRequest = bllRequest;
            _httpClientServer = httpClientServer;
            _risServer=risServer;
            _options = options.Value;
        }

        /// <summary>
        /// 上传预约信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<UploadResult> UploadAppointInfoAsync(List<UploadDto> input)
        {
            _logger.LogInformation($"上传预约信息入参:{input.ToJson()}");
            var sheetList = input.Select(t => t.SheetId).ToList();

            #region 上传预约信息

            try
            {
                if (input.First().OperateType == 4 || input.First().OperateType == 9)
                {
                    var dtos = await _bllRequest.GetReservationDtoAsync(sheetList.ToStringJoin(), input.First().OperateType.ToString());
                    if (!dtos.Any())
                    {
                        _logger.LogInformation("Proc_GetReservationInfo获取的数据为空，所以不进行上传预约信息到平台操作");
                        return new UploadResult() { Result = true };
                    }
                    var result = await _httpClientServer.UploadResAsync(dtos);
                    var error = result.Where(t => t.SendStatus == 0).ToList();
                    if (error.Any())
                    {
                        await _bllRequest.AddLogUploadResAsync(error);
                    }
                }
                else if (input.First().OperateType == 5)
                {
                    var dtos = await _bllRequest.GetReservationDtoAsync(sheetList.ToStringJoin(), input.First().OperateType.ToString());
                    if (!dtos.Any())
                    {
                        _logger.LogInformation("Proc_GetCancelAppointInfo获取的数据为空，所以不进行上传取消预约信息到平台操作");
                        return new UploadResult() { Result = true };
                    }
                    await _httpClientServer.UploadCancelResAsync(dtos);
                }

            }
            catch (Exception ex)
            {
                _logger.LogError($"上传预约信息异常:{ex}");
            }

            #endregion

            #region RIS流程

            try
            {
                _logger.LogInformation($"当前RIS模式为{_options.RegisterOrCheckIn}，预约操作类型为{input.First().OperateType}");

                if (input.First().OperateType == 4 || input.First().OperateType == 9)
                {
                    var dtoList = await _bllRequest.GetCheckInOrRegisterDtoAsync(sheetList, EnumRisOperateFlag.AutoCheckIn);
                    if (!dtoList.Any())
                    {
                        _logger.LogInformation("存储获取的数据为空，所以不进行登记,报到,更新登记操作");
                        return new UploadResult() { Result = true };
                    }

                    if(input.First().OperateType == 4 && _options.RegisterOrCheckIn == "Register")
                    {
                        var dtoinput = MapperHelper.CreateCheckInOrRegisterDto(dtoList, EnumRisOperateFlag.Register);
                        var result = await _risServer.RegisterAsync(dtoinput);
                        if (!string.IsNullOrEmpty(result.Error))
                        {
                            throw new Exception(result.Error);
                        }
                        var updates = new List<UpdateStateDto>();
                        foreach (var item in result.RespData.list)
                        {
                            var update = new UpdateStateDto();
                            update.SheetID = item.requisitionState.sheetID;
                            update.StateType = "9";
                            update.StateResult = item.requisitionState.stateResult.ToString();
                            update.ExamDate = item.requisitionState.operatorDate;
                            update.ExamTime = item.requisitionState.operatorTime;
                            update.OperatorID = item.requisitionState.operatorID;
                            update.OperatorName = item.requisitionState.operatorName;
                            update.RequisitionID = item.requisitionState.ris_requisitionid;
                            update.RequestDomain = item.requisitionState.requestDomain;
                            updates.Add(update);
                        }
                        _logger.LogInformation($"预约即登记调用存储更新检查状态:{updates.ToJson()}");
                        await _bllRequest.UpdateRequestStateAsync(updates);
                        _logger.LogInformation($"预约即登记调用存储更新检查状态完成");
                    }
                    if (input.First().OperateType == 4 && _options.RegisterOrCheckIn == "CheckIn")
                    {
                        var dtoinput = MapperHelper.CreateCheckInOrRegisterDto(dtoList, EnumRisOperateFlag.AutoCheckIn);
                        var result = await _risServer.CheckInAsync(dtoinput);
                        if (!string.IsNullOrEmpty(result.Error))
                        {
                            throw new Exception(result.Error);
                        }
                    }
                    if (input.First().OperateType == 9 && _options.RegisterOrCheckIn == "Register")
                    {
                        var dtoinput = MapperHelper.CreateUpdateRegisterDto(dtoList);
                        var result = await _risServer.UpdateRegisterAsync(dtoinput);
                        if (!string.IsNullOrEmpty(result.Error))
                        {
                            throw new Exception(result.Error);
                        }
                    }
                }
                else if(input.First().OperateType == 5)
                {
                    var dtoList = await _bllRequest.GetCancelRegisterDtoAsync(sheetList);
                    if (!dtoList.Any())
                    {
                        _logger.LogInformation("存储获取的数据为空，所以不进行取消登记或者取消报到");
                        return new UploadResult() { Result = true };
                    }
                    var dtoinput = MapperHelper.CreateCancelRegisterDto(dtoList, sheetList);
                    var result = await _risServer.CancelRegisterOrCheckInAsync(dtoinput);
                    if (!string.IsNullOrEmpty(result.Error))
                    {
                        throw new Exception(result.Error);
                    }
                }

                _logger.LogInformation($"预约后RIS流程流程结束");
            }
            catch (Exception ex)
            {
                _logger.LogInformation("预约后RIS流程异常，" + ex);
                return new UploadResult() { Result = false, Message = ex.Message };
            }

            #endregion

            return new UploadResult() { Result = true };
        }

        [HttpPost]
        public async Task<AjaxResponse<ResSetStateDto>> SetRequestionStatus_RIS(RqSetStateDto input)
        {
            _logger.LogInformation($"入参：{input.ToJson()}");
            AjaxResponse<ResSetStateDto> ajaxResponse = new() { FlagInfo = new FlagInfo { Success = true } };

            var updates = new List<UpdateStateDto>();
            var resultList = new List<ResSetStateDtoItem>();
            try
            {
                foreach (var item in input.List)
                {
                    var update = new UpdateStateDto();
                    update.SheetID = item.RequisitionState.sheetid;
                    update.StateType = item.RequisitionState.statetype;
                    update.StateResult = item.RequisitionState.stateresult;
                    update.ExamDate = item.RequisitionState.operatordate;
                    update.ExamTime = item.RequisitionState.operatortime;
                    update.OperatorID = item.RequisitionState.operatorid;
                    update.OperatorName = item.RequisitionState.operatorname;
                    update.RequisitionID = item.RequisitionState.ris_requisitionid;
                    update.RequestDomain = item.RequisitionState.requestdomain;
                    updates.Add(update);
                    resultList.Add(new ResSetStateDtoItem
                    {
                        SheetID = item.RequisitionState.sheetid,
                        StateType = Convert.ToInt32(item.RequisitionState.statetype),
                        StateResult = Convert.ToInt32(item.RequisitionState.stateresult),
                        Result = 1
                    });
                }
                _logger.LogInformation($"更新预约库的申请单号:{updates.ToJson()}");
                await _bllRequest.UpdateRequestStateAsync(updates);
                _logger.LogInformation($"更新预约库的检查状态完成");
                ajaxResponse.Result = new ResSetStateDto { List = resultList };

            }
            catch (Exception ex)
            {
                _logger.LogError("异常：" + ex);
                ajaxResponse.FlagInfo.Success = false;
                ajaxResponse.FlagInfo.Message = "异常";
                ajaxResponse.Result = new ResSetStateDto { List = new List<ResSetStateDtoItem>() };

            }
            return ajaxResponse;
        }

        /// <summary>
        /// 推送预约回执单打印状态
        /// </summary>
        /// <param name="requestInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UploadReservationPrintState(RequestInfo requestInfo)
        {
            return await Task.FromResult(1);
        }
    }
}
